Rounding numbers
Problem
You want to round numbers.
Solution
A short description of the solution.
x <- seq(-2.5, 2.5, by=.5) # -2.5 -2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0 2.5 # Round to nearest, with .5 values rounded to even number. round(x) # -2 -2 -2 -1 0 0 0 1 2 2 2 # Round up ceiling(x) # -2 -2 -1 -1 0 0 1 1 2 2 3 # Round down floor(x) # -3 -2 -2 -1 -1 0 0 1 1 2 2 # Round toward zero trunc(x) # -2 -2 -1 -1 0 0 0 1 1 2 2
It is also possible to round to other values besides one:
x <- c(.001, .07, 1.2, 44.02, 738, 9927) # 0.001 0.070 1.200 44.020 738.000 9927.000 # Round to one decimal place round(x, digits=1) # 0.0 0.1 1.2 44.0 738.0 9927.0 # Round to tens place round(x, digits=-1) # 0 0 0 40 740 9930 # Round to nearest 5 round(x/5)*5 # 0 0 0 45 740 9925 # Round to nearest .02 round(x/.02)*.02 # 0.00 0.08 1.20 44.02 738.00 9927.00